package com.shop.cereshop.app.tencent.im.pay;

import com.shop.cereshop.app.dao.wallet.BuyerWalletDAO;
import com.shop.cereshop.app.dao.wallet.WalletTransactionDAO;
import com.shop.cereshop.app.exception.BusinessException;
import com.shop.cereshop.app.param.wallet.WalletPayCheckResult;
import com.shop.cereshop.app.service.wallet.BuyerWalletService;
import com.shop.cereshop.commons.config.RsaProperties;
import com.shop.cereshop.commons.constant.CoReturnFormat;
import com.shop.cereshop.commons.domain.wallet.BuyerWallet;
import com.shop.cereshop.commons.domain.wallet.WalletTransaction;
import com.shop.cereshop.commons.utils.EmptyUtils;
import com.shop.cereshop.commons.utils.RandomStringUtil;
import com.shop.cereshop.commons.utils.RsaUtils;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @description: 红包和转账付款、退款实现类
 * @author zdd
 * @date 2025/9/8 11:28
 * @version 1.0
 */
@Slf4j
@Service
public class TimWalletPayService {

    @Resource
    private BuyerWalletDAO buyerWalletDAO;
    @Resource
    private WalletTransactionDAO walletTransactionDAO;
    @Resource
    private BuyerWalletService buyerWalletService;



    /**
     * 验证用户支付密码是否正确 和 钱包余额是否足够支付红包
     * @param buyerUserId 用户ID
     * @param amount 红包金额（单位：元）
     * @param password 支付密码
     * @return 验证结果
     */
    public WalletPayCheckResult verifyWallet(Long buyerUserId, BigDecimal amount, String password) {
        //  验证支付密码
        if (StringUtils.isBlank( password)) {
            return WalletPayCheckResult.failure(
                    "支付密码不能为空",
                    CoReturnFormat.PAY_PASSWORD_VERIFY_FAIL
            );
        }
//        boolean validPassword = isPayPasswordValidFormat(password);
//        if (!validPassword) {
//            return WalletPayCheckResult.failure(
//                    "支付密码格式错误，请输入6位数字",
//                    CoReturnFormat.PAY_PASSWORD_VERIFY_FAIL
//            );
//        }
        // 获取用户钱包
        BuyerWallet wallet = buyerWalletService.getOrCreateWallet(buyerUserId);

        // 检查余额是否足够
        if (wallet.getBalance().compareTo(amount) < 0) {
            return WalletPayCheckResult.failure(
                    String.format("钱包余额不足，当前余额：%.2f，需要支付：%.2f", wallet.getBalance(), amount),
                    CoReturnFormat.WALLET_BALANCE_INSUFFICIENT
            );
        }
        return WalletPayCheckResult.success(
                "钱包余额充足，可以支付",
                amount.toString(),
                wallet.getBalance().toString()
        );
    }

    /**
     * 验证支付密码格式
     */
    public boolean isPayPasswordValidFormat(String password) {
        String psw = decryptPayPassword(password);
        return psw != null && psw.matches("^\\d{6}$");
    }

    /**
     * 解密支付密码
     */
    public String decryptPayPassword(String password) {
        if (EmptyUtils.isEmpty(password)) {
            return null;
        }
        try {
            return RsaUtils.decryptByPrivateKey(RsaProperties.privateKey, password);
        } catch (Exception e) {
            throw new RuntimeException("支付密码解密失败", e);
        }
    }

    /**
     * 使用用户钱包支付
     * @param consumeType 交易类型
     * @param buyerUserId 用户ID
     * @param orderId 订单ID（如：packetId、transferId）
     * @param deductAmount 需要扣减的红包金额（单位：元）
     * @param payPassword 支付密码
     * @return 支付结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean walletConsume(Integer consumeType, Long buyerUserId, String orderId, BigDecimal deductAmount, String payPassword, String ipAddress) {
        // 生成钱包支付订单号
        String walletOrderNo = "WALLET" + orderId + RandomStringUtil.getRandomCode(3, 0);
        return buyerWalletService.consume(buyerUserId, deductAmount, consumeType, "单号：" + orderId, walletOrderNo, payPassword, ipAddress);
    }

    /**
     * 增加红包金额到用户钱包，并记录交易流水
     * @param buyerUserId 用户ID
     * @param orderId 单号
     * @param addAmount 增加的红包金额（单位：元）
     * @param transactionType 交易类型
     * @param desc 描述
     * @return 增加结果
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean addWalletBalance(Long buyerUserId, String orderId, BigDecimal addAmount, Integer transactionType, String desc) {
        try {
            // 获取钱包
            BuyerWallet wallet = buyerWalletService.getOrCreateWallet(buyerUserId);
            // 计算新余额
            BigDecimal newBalance = wallet.getBalance().add(addAmount);
            // 更新钱包余额
            String updateTime = TimeUtils.yyMMddHHmmss();
            int result = buyerWalletDAO.updateBalance(buyerUserId, newBalance, updateTime);
            if (result > 0) {
                // 记录交易流水
                WalletTransaction transaction = new WalletTransaction();
                transaction.setBuyerUserId(buyerUserId);
                transaction.setTransactionType(transactionType);
                transaction.setAmount(addAmount);
                transaction.setBalanceBefore(wallet.getBalance());
                transaction.setBalanceAfter(newBalance);
                transaction.setDescription(desc);
                transaction.setOrderId(orderId);
                transaction.setCreateTime(updateTime);
                walletTransactionDAO.insert(transaction);
                log.info("用户{}余额更新成功，变动金额：{}，新余额：{}", buyerUserId, addAmount, newBalance);
                return true;
            }
            return false;
        } catch (Exception e) {
            log.error("更新用户{}余额失败", buyerUserId, e);
            throw new BusinessException("更新用户余额失败: " + e.getMessage());
        }
    }



}
